import jwt
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.response import Response
from user.models import UserModel
from utils.jwttool import tooljwt


class MyAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION', '')
        if not token:
            raise AuthenticationFailed('认证失败,请先登录')
        try:
            re_token = token.split(' ')[1]
            payload = tooljwt.checkToken(re_token)
            user = UserModel.objects.get(id=payload['userid'])
            return user, payload
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed("token已过期")
        except jwt.InvalidTokenError:
            raise AuthenticationFailed("无效的token")
